package com.globallogic.vkulyk.SSHTool;

import java.io.File;
import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CLITargetModeHandler {
	private String[] args = null;
	private String targetsFile = "targets.xml";
	private String target = "";

	private SocketsAndActionsDataKeeper socketsAndActionsData = null;
	private List<SocketDataKeeper> socketsData = null;
	private List<ActionDataKeeper> actionsData = null;

	private final Logger logger = LoggerFactory
			.getLogger(CLITargetModeHandler.class);

	public CLITargetModeHandler(String[] args) {
		this.args = args;
	}

	public void run() {
		getDataFromCLI(); 
		getDataFromXML();
		convertDataToExecutorFormat();
		callExecutor();
	}

	private void getDataFromCLI() {
		logger.debug("Parsing arguments..");
		String argsInOneString = "";
		for (String arg : args) {
			argsInOneString = argsInOneString.concat(" " + arg);
		}
		// [ -f /dir/targets.xml] -t myTarget OR vice versa
		target = argsInOneString.replaceFirst("^.* -t ", "").replaceFirst(
				" .*$", "");
		if (argsInOneString.contains(" -f ")) {
			targetsFile = argsInOneString.replaceFirst("^.* -f ", "")
					.replaceFirst(" .*$", "");
		}
		if (!new File(targetsFile).exists()) {
			logger.error("ERROR: Targets file {} is not found", targetsFile);
			System.exit(1);
		}
	}

	private void getDataFromXML() {
		logger.debug("Parsing data from XML file..");
		socketsAndActionsData = new XMLHandler(targetsFile, target).parseXML();
	}

	private void convertDataToExecutorFormat() {
		logger.debug("Converting data for sending to executor..");
		socketsData = socketsAndActionsData.getSockets();
		actionsData = socketsAndActionsData.getActions();
	}

	private void callExecutor() {
		logger.debug("Calling executor..");
		new ActionsOnSocketsExecutor(socketsData, actionsData).execute();
	}
}
